package com.gzx.asr.utils;

import com.gzx.asr.constant.ModeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 解析asr时间戳
 */
@Slf4j
public class TimestampUtil {
    public static String formatTimestamp(long millis) {
        long hours = millis / 3600000;
        long remaining = millis % 3600000;
        long minutes = remaining / 60000;
        remaining %= 60000;
        long seconds = remaining / 1000;
        long ms = remaining % 1000;
        return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, ms);
    }

    public static void main(String[] args) {
        String input = "[[1300,1660],[2300,2660]]";
        String stamp = getTimeStamp(input);
        log.info("时间戳: {}", stamp);
        String timeStamp = getTalkTimeStamp("2023-07-05 09:00:00.200", stamp);
        log.info("说话的时间戳: {}", timeStamp);
    }

    //接通时间+说话的时间戳
    public static String getTalkTimeStamp(String baseTime, String addDuration) {
        if (ObjectUtils.isEmpty(baseTime) || (ObjectUtils.isEmpty(addDuration))) {
            return "";
        }
        // 定义时间解析格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        // 解析原始时间
        LocalDateTime dateTime = LocalDateTime.parse(baseTime, formatter);

        // 解析待加时间
        String[] parts = addDuration.split(":");
        long totalSeconds = Long.parseLong(parts[2].split("\\.")[0]);
        long nanoAdjustment = parts[2].contains(".")
                ? Long.parseLong(parts[2].split("\\.")[1]) * 1_000_000  // 转换为纳秒
                : 0;

        // 创建Duration对象
        Duration duration = Duration.ofHours(Long.parseLong(parts[0]))
                .plusMinutes(Long.parseLong(parts[1]))
                .plusSeconds(totalSeconds)
                .plusNanos(nanoAdjustment);

        // 执行时间相加
        LocalDateTime result = dateTime.plus(duration);

        // 输出结果（不包含毫秒）
        return result.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    //获取第一个时间戳的时分秒毫秒
    public static String getTimeStamp(String input) {
        if (ObjectUtils.isEmpty(input)) {
            return "";
        }
        // 提取第一个二维数组
        int firstStart = input.indexOf('[') + 2;  // 跳过前两个[[
        int firstEnd = input.indexOf(']');         // 找到第一个]
        String firstArray = input.substring(firstStart, firstEnd);

        // 分割两个数值
        String[] parts = firstArray.split(",");

        int start = Integer.parseInt(parts[0].trim());

        return TimestampUtil.formatTimestamp(start);
    }

    //如果两个timestamp的时间间隔小于一个固定值，则认为这两句话是同一个人说的
    public static boolean isSameSpeaker(String timestamp1, String timestamp2) {
        if (!StringUtils.hasText(timestamp1) || !StringUtils.hasText(timestamp2)) {
            return false;
        }
        //第一句话有多长
        int length = timestamp1.split(",").length;
        //第一句话的结束时间
        long end = Long.parseLong(timestamp1.split(",")[length - 1].replace("]", ""));
        //第二句话的开始时间
        long start = Long.parseLong(timestamp2.split(",")[0].replace("[", ""));
        long result = start - end;
        log.info("两句话的间隔时间 {} ", result);
        if (result <= ModeConstant.SPEAK_INTERVAL) {
            return true;
        }
        return false;
    }

}
